#!/usr/bin/env python
#-*-coding:utf-8-*-
# ---------------------------------
# version:  1.0
#
# create-time:      <2008/12/20 04:49:58>
# last-update-time: <halida 12/20/2008 12:50:34>
# ---------------------------------
# module : set loop schedule


from qtlib import *

def editLoop(parent,loopCondition=None):
    class LoopDialog(QDialog):
        loopCondition = None
        KEYS = {'hour':24,
                'day':31,
                'month':12,
                'weekday':7,
                'minute':60}
        def __init__(self,*args):
            QDialog.__init__(self,*args)
            self.lists = {}
            self.layout = QHBoxLayout(self)
            for key,value in self.KEYS.iteritems():
                #set list
                lw = QListWidget()
                lw.setSelectionMode(QAbstractItemView.MultiSelection)
                for i in range(0,value):
                    lw.addItem(str(i))
                self.lists[key]= lw
                #set layout
                l = QVBoxLayout()            
                l.addWidget(QLabel(key))
                l.addWidget(lw)
                self.layout.addLayout(l)
            #button panel
            bl = QVBoxLayout()
            self.okButton = QPushButton("&Ok")
            self.cancelButton = QPushButton("&Cancel")
            self.testButton = QPushButton("&Test")
            conn(self.okButton,"clicked(bool)",self.ok)
            conn(self.cancelButton,"clicked(bool)",self.cancel)
            conn(self.testButton,"clicked(bool)",self.test)
            bl.addWidget(self.okButton)
            bl.addWidget(self.cancelButton)
            bl.addWidget(self.testButton)
            bl.addStretch(1)

            self.layout.addLayout(bl)

        def setup(self,loopCondition):
            if not loopCondition:return
            logging.debug("loopCondition: %s",str(loopCondition))
            for key,values in loopCondition.iteritems():
                for index in values:
                    logging.debug("selecting:%s",str(index))
                    item = self.lists[key].item(index)
                    item.setSelected(True)

        def ok(self):
            #get loop condition
            lc = {}
            for key in self.KEYS:
                items = self.lists[key].selectedItems()
                lc[key] = map(lambda i:int(i.text()),items)
            LoopDialog.loopCondition = lc
            self.close()

        def cancel(self):
            LoopDialog.loopCondition = None            
            self.close()

        def test(self):
            self.lists['hour'].setCurrentRow(0)

    l = LoopDialog()
    l.setup(loopCondition)
    l.exec_()
    logging.debug(LoopDialog.loopCondition)
    return LoopDialog.loopCondition,LoopDialog.loopCondition

